/**
 * Created by wentan on 2018/12/11.
 */
const { JJUser, JJUserAccount, Ctcdb } = require('../../models/ctcdb');
const BaseResp = require('../../utils/baseResp');
const errorCode = require('../../utils/errorCode');
const jwtHandler = require('../../utils/jwtHanlder');
const request = require('request');
const getConfig = require('../../utils/configUtil').getConfig;

async function getCode2Session(code) {
  const wxAppId = getConfig.wechat.appId;
  const secret = getConfig.wechat.secret;
  let uri = 'https://api.weixin.qq.com/sns/jscode2session';

  uri += `?appid=${wxAppId}&secret=${secret}&js_code=${code}&grant_type=authorization_code`;

  return new Promise((resolve, reject) => {
    return request({
      uri,
      method: 'GET',
      timeout: 20000
    }, (err, response, body) => {
      if (err) {
        return reject(err);
      }
      try {
        body = JSON.parse(body);
        if (body.errcode) {
          return reject(BaseResp.error(errorCode.wxchat.getOpenIdError, body.errmsg));
        }
      } catch (e) {
        return reject(e)
      }
      return resolve(body);
    });
  })
}

async function loginService({ code }) {
  const {session_key, openid} = await getCode2Session(code);
  let user = await JJUser.find({
    where: {
      openId: openid
    },
    attributes: ['id'],
    raw: true
  });
  let transaction;
  let userId;
  try {
    if (!user) {
      transaction = await Ctcdb.transaction(); // 获取事务
      // 没有则创建用户
      user = await JJUser.create({
        openId: openid,
        identity: 0 // 身份标识
      }, {
        transaction
      });
      const { id } = user;
      // 创建用户的账户，在用户初始化的时候，后续就不要了
      await JJUserAccount.create({
        status: 1,
        jUserId: id
      }, {
        transaction
      });
      await transaction.commit(); // 提交事物，开启订单
    }
    userId = user.id;
    const identity = user.identity;
    const token = jwtHandler.sign({
      openid,
      session_key,
      userId
    });
    return {
      token,
      userInfo: {
        userId,
        identity,
        openid
      }
    }
  } catch (e) {
    if (transaction) {
      await transaction.rollback();
    }
    return Promise.reject(e)
  }
}

module.exports = {
  login: loginService
};
console.log(jwtHandler.sign({
  userId: 27
}));
